<template>
  <div :updateStatusData="updateStatusData" class="clearfix" v-loading="loading" element-loading-text="请稍后..." element-loading-spinner="el-icon-loading" element-loading-background="#f7f7f7">
    <div class="fromBox left" style="position: relative">
      <!-- chegn-->
      <el-form :label-position="labelPosition" label-width="83px" :model="fromData" :rules="rules" ref="fromData">
        <el-form-item :label="languageData.id=='Chinese'?'国家':'country'" >
          <el-select v-model="fromData.country"  @change="cityChange('country')" :placeholder="languageData.id=='Chinese'?'请选择':'country'">
            <el-option v-for="item in options" :key="item.code" :label="languageData.id=='Chinese'?item.CN:item.EN" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="languageData.id=='Chinese'?'省份（州）':'province'" v-show="provinceCheck">
          <el-select v-model="fromData.province"  @change="cityChange('province')" :placeholder="languageData.id=='Chinese'?'请选择':'province'">
            <el-option v-for="item in provincePtions" :key="item.code" :label="languageData.id=='Chinese'?item.CN:item.EN" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="languageData.id=='Chinese'?'城市':'city'" prop="city" >
          <el-select v-model="fromData.city"  @change="cityChange('city')" :placeholder="languageData.id=='Chinese'?'请选择':'city'">
            <el-option v-for="item in cityPtion" :key="item.code" :label="languageData.id=='Chinese'?item.CN:item.EN" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
          <div style="text-align: center">
            <el-button type="primary" round class="submit" v-on:click="submitForm('fromData')"> {{languageData.id=='Chinese'?'选择':'Selected'}} </el-button>
          </div>
      </el-form>
      <div style="position: absolute;width: 100%;left: 0px; top: -30px; font-weight: bold" ><p style="text-align: center">{{languageData.admin.checkCity}}</p></div>
      <!-- 表单-->
    </div>
    <div class="cityBox left" style="position: relative">
      <div class="ctiye" :cityList="cityList">
        <div v-for="list in countryData" style="text-align: left">
          <div class="contyName">
            <span class="Country">
                          {{languageData.id=='Chinese'?list.country.CN:list.country.EN}}</span>
            <div class="cleae"></div>
          </div>
          <div class="cityList" >
            <div v-for="lis in list.country.province" style="font-size: 12px;line-height: 30px;">
             <span v-show="languageData.id=='Chinese'">{{lis.CN?lis.CN+'：':''}} </span>
              <span v-show="languageData.id!='Chinese'">{{lis.EN?lis.EN+'：':''}} </span>
              <span class="cityBoxText" v-for="li in lis.city">
                {{languageData.id=='Chinese'?li.CN:li.EN}}
                <i class="el-icon-circle-close" @click.stop="delCityFn(li.id)"></i>
                         </span>
            </div>
          </div>
        </div>
      </div>
      <el-button type="primary" round  class="submit" :disabled="submintA" v-on:click="updateCity()" style="margin: 0px;margin-top: 10px" >{{languageData.id == 'Chinese'?'提交':'Submit'}}  </el-button>
      <div style="position: absolute;width: 100%;left: 0px; top: -30px; font-weight: bold"><p>{{languageData.admin.CompanyCity}}</p></div>
    </div>
  </div>
</template>
<style scoped>
  form {height: 289px}
  .submit{ width: 130px;height: 34px;line-height: 0px;margin-top:69px;}
   .cityBox{width:500px;height:295px;border: 1px solid #e1e1e1; margin-left:20px;background-color: white;padding:  20px; border-radius:8px; box-shadow:0 0 16px #e2e7ea; }
  .ctiye{width:500px;height:265px;overflow-y: scroll; }
  .fromBox{width: 300px;border: 1px solid #e1e1e1;margin-left:20px;background-color: white;padding: 40px 20px 40px 20px; border-radius:8px; box-shadow:0 0 16px #e2e7ea;padding-bottom: 6px }
  .Country{font-weight: bold;}
  .cityList{ padding-left: 20px;}
  .contyName{padding-top: 20px;}
  .cityBoxText{padding: 5px 10px; cursor: pointer}
</style>
<script>
  import UserImg from '../../../static/img/icon/userDeFilt.png'
  import jsonListData from '../../../static/local.json'
  import {mapState, mapActions} from 'vuex'
  export default {
    name: 'my-cityList',
    created () {
      // 查看本页面路由 绑定对应页面class
      var usr = sessionStorage.getItem('user')
      if(usr) {
        usr = JSON.parse(usr)
        this.user = usr
      }
    },
    data () {
      var indeofCity = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请选择城市'));
        }
        setTimeout(() => {
          if (this.getlist.data.indexOf(this.fromData.city) >= 0) {
            return callback(new Error('该城市已有'));
          }else {
            callback();
          }
        }, 300);
      };
      return {
        loading: false,
        submintA: true,
        labelPosition: 'left',
        user: {
          imgUlr: UserImg, // 账号图片
          name: '小明管理员'
        },
        fromData: {
          country: null, // 国家
          province: null, // 省份州
          city: null // 密码
        },
        rules: {
          country: [
            { required: true, message: '请输入用户商家名', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
          province: [
            { required: true, message: '请输入登陆账号', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
          city: [
            { validator: indeofCity, trigger: 'change' },
          ]
        },
        left: 'left',
        getlist: {data: []},
        options: [{
          code: '1',
          CN: '',
          EN: ''
        }],
        provincePtions: [{
          code: '',
          CN: '',
          EN: ''
        }],
        cityPtion: [{
          code: '',
          CN: '',
          EN: ''
        }],
        provinceCheck: true,
        countryData: [{
          country: {
            id: null,
            CN: null,
            EN: null,
            province: [{
              id: null,
              CN: null,
              EN: null,
              city: [{
                id: null,
                CN: null,
                EN: null
              }]
            }]
          }
        }]
      }
    },
    methods: {
      ...mapActions({
        setCityPost: 'setCityList',
        getCityList: 'getCityList'
      }),
      tableRowClassName ({row, rowIndex}) {
        var x = rowIndex % 2
        if (x === 0) {
          return ''
        } else if (x === 1) {
          return 'success-row'
        }
        return ''
      },
      handleCurrentChange (val) {
      },
      login () {
        this.$router.push({ name: "map" })
      },
      submitForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.submintA = false
            // 添加到本地城市列表
            this.getlist.data.push(this.fromData.city)
            // 重新编译界面
            this.cityListFn(this.getlist)
            // 清空 表单
            this.fromData.country = ''
            this.fromData.province = ''
            this.fromData.city = ''
            // 清空 城市列表
            this.cityPtion = [{
              code: '',
              CN: '',
              EN: ''
            }]
            this.provincePtions = [{
              code: '',
              CN: '',
              EN: ''
            }]
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 城市列表展示
      cityListFn (res) {
        this.getlist = res
        res = res.data
        var cityData = []
        for (let i in res) {
          // 拉取本地地址世界地址jsom
          var DATA = jsonListData
          // 申明单次循环地址
          var address = {
            country: {CN: '', id: '', EN: ''},
            province: {CN: '', id: '', EN: ''},
            city: {CN: '', id: '', EN: ''}
          }
          // 切割地址 分离国家城市
          var list = res[i].split('_')
          // 注入国家id
          address.country.id = list[0]
          address.country.CN = DATA[address.country.id].CN
          address.country.EN = DATA[address.country.id].EN
          if (list) {
            // 注入省份id
            address.province.id = address.country.id + '_' + list[1]
            address.province.CN = DATA[address.country.id][address.province.id].CN
            address.province.EN = DATA[address.country.id][address.province.id].EN
            // 注入城市id
            address.city.id = address.province.id + '_' + list[2]
            address.city.CN = DATA[address.country.id][address.province.id][address.city.id].CN
            address.city.EN = DATA[address.country.id][address.province.id][address.city.id].EN
          }
          cityData.push(address)
        }
        // 国家去重
        var result = [], result2 = [], hash = {};
        // 提出所有国家 和 重复的国家
        for (var i = 0; i < cityData.length; i++) {
          var elem = cityData[i].country.id
          if (!hash[elem]) {
            result.push({
              country: {
                id: cityData[i].country.id,
                CN: cityData[i].country.CN,
                EN: cityData[i].country.EN,
                province: [{
                  id: cityData[i].province.id,
                  CN: cityData[i].province.CN,
                  EN: cityData[i].province.EN,
                  city: [{
                    id: cityData[i].city.id,
                    CN: cityData[i].city.CN,
                    EN: cityData[i].city.EN
                  }]
                }]
              }
            })
            hash[elem] = true
          } else {
            result2.push({
              pid: cityData[i].country.id,
              id: cityData[i].province.id,
              CN: cityData[i].province.CN,
              EN: cityData[i].province.EN,
              city: [{
                id: cityData[i].city.id,
                CN: cityData[i].city.CN,
                EN: cityData[i].city.EN
              }]})
          }
        }
        // 组装 城市列表
        for (let i in result2) {
          for (let k in result) {
            var bol1 = true
            if (result2[i].pid == result[k].country.id){
              for (let s in result[k].country.province){
                if (result2[i].id == result[k].country.province[s].id){
                  var da = result[k].country.province[s].city
                  var da2 = result2[i].city
                  var dat3 = da.concat(da2)
                  bol1 = false
                  result[k].country.province[s].city = dat3
                }
              }
              if (bol1) {
                result[k].country.province.push(result2[i])
              }
            }
          }
        }
        // 选择城市
        this.countryData = result
      },
      // 城市下拉框
      cityChange(type){
        if(type == 'country'){
          var parm = jsonListData[this.fromData.country]
          // 提取国家省份数据
          this.provincePtions = this.citPotin(parm,'country');
          // 清空 省份和城市
          this.fromData.province = ''
          this.fromData.city = ''
          // 查看有无省份
          if( this.provincePtions[0].check){
            // 隐藏省份选项
            this.provinceCheck = false
            // 赋值省份coede
            this.fromData.province = this.provincePtions[0].code
            // 自动执行寻找城市
            type = 'province'
          }else {
            // 开放省份选择
            this.provinceCheck = true
            type = 'country'
          }
        }
        // 从省份数据提取城市列表
        if(type == 'province'){
          var parm = jsonListData[this.fromData.country][this.fromData.province]
          // 提取城市列表
          this.cityPtion = this.citPotin(parm)
          // 清空城市
          this.fromData.city = ''
        }
        if(type == 'city'){
          // 此处判断城市是否已被选择，放在验证表达里面去做了
        }
      },
      // 选择城市
      citPotin(data,type){
        var result = []
        var res = {code:null, EN:null, CN:null}
        for (let i in data){
          if(type = 'country'){
            // 从国家数据提取省份列表
              if(data[i].EN){ // 筛选有省份名称的（国家有三级地区）
                res = {code:i, EN:data[i].EN, CN:data[i].CN,}
                result.push(res)
              }else {
                if(typeof(data[i]) == 'object'){// 过滤名称
                  res = {code:i, EN:data[i].EN|| 'Municipality', CN:data[i].CN || '直辖市',check:true}
                  result.push(res)
                }
              }
          }else {
              if(data[i].EN){ // 筛选有城市（国家有三级地区）
                res = {code:i, EN:data[i].EN, CN:data[i].CN,}
                result.push(res)
              }
          }
        }
       return result
      },
      // 提交 城市
      updateCity () {
        var uer = sessionStorage.getItem('user')
        uer = JSON.stringify(uer)
        var parm = {
          companyId: this.user.companyId,
          cityList: this.getlist.data
        }
        this.loading = true
        this.setCityPost(parm)
      },
      // 删除 城市
      delCityFn (id){
        var data = this.getlist.data
        // 放开提交权限
        this.submintA = false
        if(data.length == 1){
          // 最后一个被删除的 不放权限
          this.submintA = true
        }
       for (let i in data){
          if(id == data[i]){
            // 去掉被删除的城市
            data.splice(i,1)
            this.cityListFn(this.getlist.data)
            return
          }
       }
      },
      listStatus (res) {
        this.loading = false
        if (res.status == 0) {
          // 修改成功
          var text =  this.languageData.id=='Chinese'? '城市列表提交成功': 'City list submission success'
          this.openSuccess(text)
          var par = {
            company: this.user.companyName
          }
          this.getCityList(par);
          this.options = this.citPotin(jsonListData)
        }
        if (res.status != 0) {
          // 修改成功 修改失败
          var text =  this.languageData.id=='Chinese'? '城市列表提交失败': 'City list submit failed'
          this.openError(text)
        }
        // 清空 vuex 中的本次记录，以免被下次操作状态造成混淆
        this.$store.commit('updateStatusTo', {body: null})
      },
      openSuccess (text) {
        this.$message({
          message: text,
          type: 'success'
        })
      },
      openError (text) {
        this.$message.error(text)
      }
    },
    computed: {
      cityList: function () {
        var parm = this.cityListData
        if (parm) {
          this.cityListFn(parm.body)
        }
        return 1
      },
      updateStatusData: function () {
        var parm = this.updateStatus
        if (parm) {
          this.listStatus(parm)
        }
        return 1
      },
      languageData: function () {
        var parm = this.language
        if (parm) {
          if (parm.check == 'Chinese') {
            parm = parm.Chinese
          }
          if (parm.check == 'English') {
            parm = parm.English
//            this.formConfig.labelWidth = '200px'
//            dom.style = 'width:620px'
          }
          // 替换 其他交互数据
//          this.updateDate(parm)
        }
        return parm
      },
      ...mapState([
        'addOderData',
        'updateStatus',
        'language',
        'cityListData'
      ])
    },
    mounted () {
      var par = {
        company: this.user.companyName
      }
      this.getCityList(par);
     this.options = this.citPotin(jsonListData)
    },
    components: {
    }
  }
</script>

